package com.cskaoyan.service.impl;

import com.cskaoyan.bean.data.RegisterData;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.cskaoyan.mapper.MarketUserMapper;
import com.cskaoyan.model.*;
import com.cskaoyan.service.UserService;
import com.cskaoyan.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Author Pudding
 * @Date 2024/6/14 9:20
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    MarketUserMapper userMapper;

    @Autowired
    MarketCouponMapper couponMapper;

    @Autowired
    MarketCouponUserMapper couponUserMapper;

    @Override
    public MarketUser findByName(String username) {
        //1. 构造查询条件
        MarketUserExample example = new MarketUserExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andStatusEqualTo((byte) 0)
                .andUsernameEqualTo(username);

        //2. 进行条件查询
        List<MarketUser> marketUsers = userMapper.selectByExample(example);

        return marketUsers != null && marketUsers.size() == 1 ? marketUsers.get(0) : null;
    }

    @Override
    public MarketUser findById(Integer userId) {
        //1. 构造查询条件
        MarketUserExample example = new MarketUserExample();
        example.createCriteria().andDeletedEqualTo(false)
                .andIdEqualTo(userId)
                .andStatusEqualTo((byte) 0);

        //2. 进行条件查询
        List<MarketUser> marketUsers = userMapper.selectByExample(example);

        return marketUsers != null && marketUsers.size() == 1 ? marketUsers.get(0) : null;
    }

    /**
     * 通过电话号码查找是否该号码注册
     *
     * @param mobile
     * @return
     */
    @Override
    public boolean findByMobile(String mobile) {
        MarketUserExample userExample = new MarketUserExample();

        userExample.createCriteria().andDeletedEqualTo(false).andMobileEqualTo(mobile);
        List<MarketUser> marketUsers = userMapper.selectByExample(userExample);
        if (marketUsers == null || marketUsers.isEmpty()) {
            return true;
        }
        return false;
    }

    // try {
//     // 生成密钥对
//     Map<String, Object> keyPair = RSAUtil.genKeyPair();
//
//     // 获取公钥和私钥
//     String publicKey = RSAUtil.getPublicKey(keyPair);
//     String privateKey = RSAUtil.getPrivateKey(keyPair);
//     // 使用公钥加密密码
//     byte[] encryptedPassword = RSAUtil.encryptByPublicKey(password.getBytes(), publicKey);
//
//     // 存储加密后的密码
//     byte[] encryptedPasswordStr = Base64Util.encode(encryptedPassword);
//     marketUser.setPassword(Arrays.toString(encryptedPasswordStr));
//     System.out.println("Encrypted Password: " + encryptedPasswordStr);
//
//     // 模拟解密过程（在实际应用中，解密过程应该在服务器端进行）
//     byte[] decryptedPassword = RSAUtil.decryptByPrivateKey(encryptedPasswordStr, privateKey);
//     System.out.println("Decrypted Password: " + new String(decryptedPassword));
// } catch (Exception e) {
//     throw new RuntimeException(e);
// }
    /**
     * 添加新用户，并添加相应的优惠券
     *
     * @param username
     * @param password
     * @param mobile
     * @param remoteAddr
     * @return
     */
    @Override
    public RegisterData addNewUser(String username, String password, String mobile, String remoteAddr) {
        RegisterData registerData = new RegisterData();

        MarketUser marketUser = new MarketUser();
        marketUser.setUsername(username);
        String[] minEnglish = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        String[] maxEnglish = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        String[] numbers = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        Random r = new Random();
        int index = 0;
        StringBuffer stringBuffer = new StringBuffer();
        // 生成7位随机字符串当nickname，不返回username
        while (index < 7) {
            int numberRandom = r.nextInt(3);
            if (numberRandom == 0) {
                int numberMinEnglish = r.nextInt(26);
                stringBuffer.append(minEnglish[numberMinEnglish]);
            } else if (numberRandom == 1) {
                int numberMaxEnglish = r.nextInt(26);
                stringBuffer.append(maxEnglish[numberMaxEnglish]);
            } else {
                int number = r.nextInt(10);
                stringBuffer.append(numbers[number]);
            }
            index++;
        }

        marketUser.setNickname(username);
        //添加默认头像
        marketUser.setAvatar("https://yanxuan.nosdn.127.net/80841d741d7fa3073e0ae27bf487339f.jpg?imageView&quality=90&thumbnail=64x64");

        String md5Password = MD5Util.getMd5(password);
        marketUser.setPassword(md5Password);
        marketUser.setAddTime(new Date());
        marketUser.setUpdateTime(new Date());
        marketUser.setLastLoginTime(new Date());
        marketUser.setMobile(mobile);
        marketUser.setLastLoginIp(remoteAddr);
        userMapper.insertSelective(marketUser);

        MarketUserExample userExample = new MarketUserExample();
        userExample.createCriteria().andUsernameEqualTo(username).andDeletedEqualTo(false);
        List<MarketUser> marketUsers = userMapper.selectByExample(userExample);
        Integer userId = marketUsers.get(0).getId();

        // 注册的优惠券 这里是领取时间的延长的优惠券
        MarketCouponExample couponExample = new MarketCouponExample();
        couponExample.createCriteria()
                .andDeletedEqualTo(false)
                .andTypeEqualTo((short) 1)
                .andTimeTypeEqualTo((short) 0);

        List<MarketCoupon> marketCoupons = couponMapper.selectByExample(couponExample);
        for (MarketCoupon marketCoupon : marketCoupons) {
            MarketCouponUser couponUser = new MarketCouponUser();
            couponUser.setUserId(userId);
            couponUser.setCouponId(marketCoupon.getId());
            couponUser.setStartTime(new Date());
            couponUser.setEndTime(new Date(System.currentTimeMillis() + marketCoupon.getDays() * 24 * 3600000));
            couponUser.setAddTime(new Date());
            couponUser.setUpdateTime(new Date());
            couponUserMapper.insertSelective(couponUser);
            if (marketCoupon.getTotal() > 0) {
                int total = marketCoupon.getTotal() - 1;
                if (total == 0){
                    marketCoupon.setDeleted(true);
                }
                marketCoupon.setTotal(total);
            }
            couponMapper.updateByPrimaryKeySelective(marketCoupon);
        }

        // 这里是截止时间和开始时间的优惠券
        couponExample.clear();
        couponExample.createCriteria().andDeletedEqualTo(false).andTimeTypeEqualTo((short) 1).andTypeEqualTo((short) 1);
        List<MarketCoupon> marketCouponList = couponMapper.selectByExample(couponExample);
        for (MarketCoupon marketCoupon : marketCouponList) {
            MarketCouponUser couponUser = new MarketCouponUser();
            couponUser.setUserId(userId);
            couponUser.setCouponId(marketCoupon.getId());
            couponUser.setStartTime(marketCoupon.getStartTime());
            couponUser.setEndTime(marketCoupon.getEndTime());
            couponUser.setAddTime(new Date());
            couponUser.setUpdateTime(new Date());
            couponUserMapper.insertSelective(couponUser);
        }


        registerData.setUserInfo(new RegisterData.UserInfo(String.valueOf(stringBuffer), "https://yanxuan.nosdn.127.net/80841d741d7fa3073e0ae27bf487339f.jpg?imageView&quality=90&thumbnail=64x64"));
        return registerData;
    }

    @Override
    public boolean userNameExist(String username) {
        MarketUserExample userExample = new MarketUserExample();
        userExample.createCriteria().andDeletedEqualTo(false).andUsernameEqualTo(username);

        List<MarketUser> marketUsers = userMapper.selectByExample(userExample);
        if (marketUsers == null || marketUsers.isEmpty()) {
            return true;
        }

        return false;
    }

    @Override
    public boolean phoneExist(String mobile) {
        MarketUserExample userExample = new MarketUserExample();
        userExample.createCriteria().andDeletedEqualTo(false).andMobileEqualTo(mobile);

        List<MarketUser> marketUsers = userMapper.selectByExample(userExample);
        if (marketUsers == null || marketUsers.isEmpty()) {
            return true;
        }
        return false;
    }

    @Override
    public void resetPassword(String mobile, String password, String remoteAddr) {
        MarketUserExample userExample = new MarketUserExample();
        userExample.createCriteria().andDeletedEqualTo(false).andMobileEqualTo(mobile);
        // 得到要修改的用户对象
        List<MarketUser> marketUsers = userMapper.selectByExample(userExample);
        MarketUser marketUser = marketUsers.get(0);
        // 修改后的加密密码
        String md5Password = MD5Util.getMd5(password);
        marketUser.setPassword(md5Password);
        marketUser.setLastLoginIp(remoteAddr);
        marketUser.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(marketUser);
    }
}
